from flask import Blueprint, request, session, render_template,redirect,url_for,jsonify
from datetime import datetime
import BaseDao
blu = Blueprint("user", __name__)


@blu.route('/myself/<int:page>/', methods=['post', 'get'])  # 用户信息
def myself(page):
    if session.get('username'):
        pagesize = 10
        sql = 'select * from blogs where status=1 or username="{}" order by id desc limit {},{}'.format(
            session["username"], (page - 1) * pagesize, pagesize)
        sql2 = 'select * from blogs where status=1 or username="{}"'.format(session["username"])
        total_page = (len(BaseDao.select_db(sql2)) // pagesize) + 1
        if page == 0 or page == total_page + 1:
            return "<script type='text/javascript'>alert('没有更多了！');history.back()</script>"
        result = BaseDao.select_db(sql)
        blogs_data = []
        for i in result:
            blogs_data.append({'blog_id': i[0],
                               'title': i[1],
                               'date': i[2],
                               'tags': " ".join(i[3].split('&')),
                               #  "details":i[4],
                               # 'status':i[5],
                               'username': i[6]
                               })
        data = {
            "blogs_data": blogs_data,
            "Previous": page - 1,
            "now_page": page,
            'total_page': total_page,
            "Next": page + 1
        }

        return render_template('myself.html', **data)
    else:
        return redirect(url_for("login.login"))


@blu.route("/publish", methods=["get", "post"])
def publish():
    if session["username"]:
        return render_template("publish.html", username=session["username"])
    else:
        return redirect(url_for("login"))


@blu.route("/publish/<int:status>/", methods=["get", "post"])
def publish_check(status):
    title = request.form.get("title")
    tags = request.form.get("tags")
    detail = request.form.get("detail")
    username = request.form.get("username")
    dt = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    code = {"status": ""}
    if status == 1:
        sql = "insert into blogs values(null ,'{}','{}','{}','{}',{},'{}')".format(title, dt, tags, detail, status,
                                                                                   username)
        if BaseDao.change_db(sql):
            code["status"] = "success"
        return jsonify(code)
    elif status == 2:
        pass
        # sql = "insert into blogs values(null ,'{}','{}','{}','{}',{},'{}')".format(title, dt, tags, detail, status,
        #                                                                            username)
        # if BaseDao.change_db(sql):
        #     code["status"] = "success"
        # return jsonify(code)
    elif status == 3:
        sql = "delete from blogs where id={}".format(request.args.get("blog_id"))
        if BaseDao.change_db(sql):
            code["status"] = "success"
        return jsonify(code)
